Multi-pass video encoding

ABSTRACT

Some embodiments of the invention provide a multi-pass encoding method that encodes several images (eg., several frames of a video sequence). The method iteratively performs an encoding operation that encodes these images. The encoding operation is based on a nominal quantization parameter, which the method uses to compute quantization parameters for the images. During several different iterations of the encoding operation, the method uses several different nominal quantization parameters. The method stops its iterations when it reaches a terminating criterion (e.g., it identifies an acceptable encoding of the images).

CLAIM OF BENEFIT

This application claims benefit of U.S. Provisional Patent Application60/583,418, filed on Jun. 27, 2004. This application also claims benefitof U.S. Provisional Patent Application 60/643,918, filed Jan. 09, 2005.These applications are incorporated herein by reference.

BACKGROUND OF THE INVENTION

Video encoders encode a sequence of video images (e.g., video frames) byusing a variety of encoding schemes. Video encoding schemes typicallyencode video frames or portions of video frames (e.g., sets of pixels inthe video frames) in terms of intraframes or interframes. An intraframeencoded frame or pixel set is one that is encoded independently of otherframes or pixels sets in other frames. An interframe encoded frame orpixel set is one that is encoded by reference to one or more otherframes or pixel sets in other frames.

When compressing video frames, some encoders implements a ‘ratecontroller,’ which provides a ‘bit budget’ for a video frame or a set ofvideo frames that are to be encoded. The bit budget specifies the numberof bits that have been allocated to encode the video frame or set ofvideo frames. By efficiently allocating the bit budgets, the ratecontroller attempts to generate the highest quality compressed videostream in view of certain constraints (e.g., a target bit rate, etc.).

To date, a variety of single-pass and multi-pass rate controllers havebeen proposed. A single-pass rate controller provides bit budgets for anencoding scheme that encodes a series of video images in one pass,whereas a multi-pass rate controller provides bit budgets for anencoding scheme that encodes a series of video images in multiplepasses.

Single-pass rate controllers are useful in real-time encodingsituations. Multi-pass rate controllers, on the other hand, optimize theencoding for a particular bit rate based on a set of constraints. Notmany rate controllers to date consider the spatial or temporalcomplexity of frames or pixel-sets within the frames in controlling thebit rates of their encodings. Also, most multi-pass rate controllers donot adequately search the solution space for encoding solutions that useoptimal quantization parameters for frames and/or pixel sets withinframes in view of a desired bit rate.

Therefore, there is a need in the art for a rate controller that usesnovel techniques to consider the spatial or temporal complexity of videoimages and/or portions of video images, while controlling the bit ratefor encoding a set of video images. There is also a need in the art fora multi-pass rate controller that adequately examines the encodingsolutions to identify an encoding solution that uses an optimal set ofquantization parameters for video images and/or portions of videoimages.

SUMMARY OF THE INVENTION

Some embodiments of the invention provide a multi-pass encoding methodthat encodes several images (e.g., several frames of a video sequence).The method iteratively performs an encoding operation that encodes theseimages. The encoding operation is based on a nominal quantizationparameter, which the method uses to compute quantization parameters forthe images. During several different iterations of the encodingoperation, the method uses several different nominal quantizationparameters. The method stops its iterations when it reaches aterminating criterion (e.g., it identifies an acceptable encoding of theimages).

Some embodiments of the invention provide a method for encoding videosequences. The method identifies a first attribute quantifying thecomplexity of a first image in the video. It also identifies aquantization parameter for encoding the first image based on theidentified first attribute. The method then encodes the first imagebased on the identified quantization parameter. In some embodiments,this method performs these three operations for several images in thevideo. Also, in some embodiments, the first attribute provides anindication of the amount of visual masking that would allow hiding mostof the compression artifacts from the sequence encoding such that theyare not visible.

BRIEF DESCRIPTION OF THE DRAWINGS

The novel features of the invention are set forth in the appendedclaims. However, for purpose of explanation, several embodiments of theinvention are set forth in the following figures.

FIG. 1 presents a process that conceptually illustrates the encodingmethod of some embodiments of the invention.

FIG. 2 conceptually illustrates a codec system of some embodiments.

FIG. 3 is a flow chart illustrating encoding process of someembodiments.

FIGS. 4 a is plot of the difference between nominal removal time andfinal arrival time of images versus image number illustrating underflowcondition in some embodiments.

FIG. 4 b illustrates plot of the difference between nominal removal timeand final arrival time of images versus image number for the same imagesshown in FIG. 4 a after the underflow condition is eliminated.

FIG. 5 illustrates a process that the encoder uses to perform underflowdetection in some embodiments.

FIG. 6 illustrates a process the encoder utilizes to eliminate underflowcondition in a single segment of images in some embodiments.

FIG. 7 illustrates an application of buffer underflow management in avideo streaming application.

FIG. 8 illustrates an application of buffer underflow management in anHD-DVD system.

FIG. 9 presents a computer system with which one embodiment of theinvention is implemented.

DETAILED DESCRIPTION OF THE INVENTION

In the following detailed description of the invention, numerousdetails, examples and embodiments of the invention are set forth anddescribed. However, it will be clear and apparent to one skilled in theart that the invention is not limited to the embodiments set forth andthat the invention may be practiced without some of the specific detailsand examples discussed.

I. DEFINITIONS

This section provides definitions for several symbols that are used inthis document.

R_(T) represents a target bit rate, which is a desired bit rate forencoding a sequence of frames. Typically, this bit rate is expressed inunits of bit/second, and is calculated from the desired final file size,the number of frames in the sequence, and the frame rate.

R_(p) represents the bit rate of the encoded bit stream at the end of apass p.

E_(p) represents the percentage of error in the bit rate at the end ofpass p. In some cases, this percentage is calculated as$100 \times {\frac{\left( {R_{T} - R_{P}} \right)}{R_{T}}.}$

ε represents the error tolerance in the final bit rate.

ε_(C) represents the error tolerance in the bit rate for the first QPsearch stage.

QP represents the quantization parameter.

QP_(Nom(p)) represents the nominal quantization parameter that is usedin pass p encoding for a sequence of frames. The value of QP_(Nom(p)) isadjusted by the invention's multi-pass encoder in a first QP adjustmentstage to reach the target bit rate.

MQP_(p)(k) represents the masked frame QP, which is the quantizationparameter (QP) for a frame k in pass p. Some embodiments compute thisvalue by using the nominal QP and frame-level visual masking.

MQP_(MB(p))(k, m) represents the masked macroblock QP, which is thequantization parameter (QP) for an individual macroblock (with amacroblock index m) in a frame k and a pass p. Some embodiments computeMQP_(MB(p))(k, m) by using MQP_(p)(k) and macroblock-level visualmasking.

φ_(F)(k) represents a value referred to as the masking strength forframe k. The masking strength φ_(F)(k) is a measure of complexity forthe frame and, in some embodiments, this value is used to determine howvisible coding artifacts/noise would appear and to compute theMQP_(p)(k) of frame k.

φ_(R(p)) represents the reference masking strength in pass p. Thereference masking strength is used to compute MQP_(p)(k) of frame k, andit is adjusted by the invention's multi-pass encoder in a second stageto reach the target bit rate.

φ_(MB)(k, m) represents the masking strength for a macroblock with anindex m in frame k. The masking strength φ_(MB)(k, m) is a measure ofcomplexity for the macroblock and, in some embodiments, it is used todetermine how visible coding artifacts/noise would appear and to computeMQP_(MB(p))(k, m). AMQP_(p) represents an average masked QP over framesin pass p. In some embodiments, this value is computed as the averageMQP_(p)(k) over all frames in a pass p.

II. OVERVIEW

Some embodiments of the invention provide an encoding method thatachieves the best visual quality for encoding a sequence of frames at agiven bit rate. In some embodiments, this method uses a visual maskingprocess that assigns a quantization parameter QP to every macroblock.This assignment is based on the realization that coding artifacts/noisein brighter or spatially complex areas in an image or a video frame areless visible than those in darker or flat areas.

In some embodiments, this visual masking process is performed as part ofan inventive multi-pass encoding process. This encoding process adjustsa nominal quantization parameter and controls the visual masking processthrough a reference masking strength parameter φ_(R), in order to havethe final encoded bit stream reach the target bit rate. As furtherdescribed below, adjusting the nominal quantization parameter andcontrolling the masking algorithm adjusts the QP values for each picture(i.e., each frame in typically video encoding schemes) and eachmacroblock within each picture.

In some embodiments, the multi-pass encoding process globally adjuststhe nominal QP and φ_(R) for the entire sequence. In other embodiments,this process divides the video sequence into segments, with the nominalQP and φ_(R) adjusted for each segment. The description below refers toa sequence of frames on which the multi-pass encoding process isemployed. One of ordinary skill will realize that this sequence includesthe entire sequence in some embodiments, while it includes only asegment of a sequence in other embodiments.

In some embodiments, the method has three stages of encoding. Thesethree stages are: (1) an initial analysis stage that is performed inpass 0, (2) a first search stage that is performed in pass 1 throughpass N₁, and (3) a second search stage that is performed in pass N₁+1through N₁+N₂.

In the initial analysis stage (i.e., during pass 0), the methodidentifies an initial value for the nominal QP (QP_(Nom(1)), to be usedin pass 1 of the encoding). During the initial analysis stage, themethod also identifies a value of the reference masking strength φ_(R),which is used in all the passes in first search stage.

In first search stage, the method performs N₁ iterations (i.e., N₁passes) of an encoding process. For each frame k during each pass p, theprocess encodes the frame by using a particular quantization parameterMQP_(p)(k) and particular quantization parameters MQP_(MB(p))(k, m) forindividual macroblocks m within the frame k, where MQP_(MB(p))(k, m) iscomputed using MQP_(p)(k).

In the first search stage, the quantization parameter MQP_(p)(k) changesbetween passes as it is derived from a nominal quantization parameterQP_(Nom(p)) that changes between passes. In other words, at the end ofeach pass p during the first search stage, the process computes anominal QP_(Nom(p+1)) for pass p+1. In some embodiments, the nominalQP_(Nom(p+1)) is based on the nominal QP value(s) and bit rate error(s)from previous pass(es). In other embodiments, the nominal QP_(Nom(p+1))value is computed differently at the end of each pass in the secondsearch stage.

In the second search stage, the method performs N₂ iterations (i.e., N₂passes) of the encoding process. As in the first search stage, theprocess encodes each frame k during each pass p by using a particularquantization parameter MQP_(p)(k) and particular quantization parametersMQP_(MB(p))(k, m) for individual macroblocks m within the frame k, whereMQP_(MB(p))(k, m) is derived from MQP_(p)(k).

Also, as in the first search stage; the quantization parameterMQP_(p)(k) changes between passes. However, during the second searchstage, this parameter changes as it is computed using a referencemasking strength φ_(R(p)) that changes between passes. In someembodiments, the reference masking strength φ_(R(p)) is computed basedon the error in bit rate(s) and value(s) of φ_(R) from previouspass(es). In other embodiments, this reference masking strength iscomputed to be a different value at the end of each pass in the secondsearch stage.

Although the multi-pass encoding process is described in conjunctionwith the visual masking process, one of ordinary skill in art willrealize that an encoder does not need to use both these processestogether. For instance, in some embodiments, the multi-pass encodingprocess is used to encode a bitstream near a given target bit ratewithout visual masking, by ignoring φ_(R) and omitting the second searchstage described above.

The visual masking and multi-pass encoding process are further describedin Sections III and IV of this application.

III. VISUAL MASKING

Given a nominal quantization parameter, the visual masking process firstcomputes a masked frame quantization parameter (MQP) for each frameusing the reference masking strength (φ_(R)) and the frame maskingstrength (φ_(F)). This process then computes a masked macroblockquantization parameter (MQP_(MB)) for each macroblock, based on theframe and macroblock-level masking strengths (φ_(F) and φ_(MB)). Whenthe visual masking process is employed in a multi-pass encoding process,the reference masking strength (φ_(R)) in some embodiments is identifiedduring the first encoding pass, as mentioned above and further describedbelow.

A. Computing the Frame-Level Masking Strength

1. First Approach

To compute the frame-level masking strength φ_(F)(k), some embodimentsuse the following equation (A):φ_(F)(k)=C*power(E*avgFrameLuma(k),β)*power(D*avgFrameSAD(k),α_(F)),  (A)

where

-   -   avgFrameLuma(k) is the average pixel intensity in frame k        computed using b×b regions, where b is an integer greater or        equal to 1 (for instance, b=1 or b=4);    -   avgFrameSAD(k) is the average of MbSAD(k, m) over all        macroblocks in frame k;    -   MbSAD(k, m) is the sum of the values given by a function        Calc4×4MeanRemovedSAD(4×4_block_pixel_values) for all 4×4 blocks        in the macroblock with index m;    -   α_(F),C, D, and E are constants and/or are adapted to the local        statistics; and    -   power(a,b) means a^(b).

The pseudo-code for the function Calc4×4MeanRemovedSAD is as follows:Calc4x4MeanRemovedSAD(4x4_block_pixel_values) {  calculate the mean ofpixel values in the given 4x4 block;  subtract the mean from pixelvalues and compute their absolute values;  sum the absolute valuesobtained in the previous step;  return the sum; }

2. Second Approach

Other embodiments compute the frame-level masking strength differently.For instance, the above-described equation (A) computes the framemasking strength essentially as follows:φ_(F)(k)=C*power(E*Brightness_Attribute,exponent0)*power(scalar*Spatial_Activity_Attribute,exponent 1).In equation (A), the frame's Brightness_Attribute equalsavgFrameLuma(k), and the Spatial_Activity_Attribute equalsavgFrameSAD(k), which is the average macroblock SAD (MbSAD(k, m)) valueover all macroblocks in a frame, where the average macroblock SAD equalsthe sum of the absolute value of the mean removed 4×4 pixel variation(as given by Calc4×4MeanRemovedSAD) for all 4×4 blocks in a macroblock.This Spatial_Activity_Attribute measures the amount of spatialinnovations in a region of pixels within the frame that is being coded.

Other embodiments expand the activity measure to include the amount oftemporal innovations in a region of pixels across a number of successiveframes. Specifically, these embodiments compute the frame maskingstrength as follows:100_(F)(k)=C*power(E*Brightness_Attribute,exponent0)*power(scalar*Activity_Attribute,exponent1)   (B)In this equation, the Activity_Attribute is given by the followingequation (C),Activity_Attribute=G*power(D*Spatial_Activity_Attribute,exponent_beta)+E*power(F*Temporal_Activity_Attribue, exponent_delta)  (C)

In some embodiments, the Temporal_Activity_Attribute quantifies theamount of distortion that can be tolerated (i.e., masked) due to motionbetween frames. In some of these embodiments, theTemporal_Activity_Attribute of a frame equals a constant times the sumof the absolute value of the motion compensated error signal of pixelregions defined within the frame. In other embodiments,Temporal_Activity_Attribute is provided by the equation (D) below:

Temporal_Activity_Attribute= $\begin{matrix}{{\sum\limits_{j = {- 1}}^{- N}\left( {W_{j} \cdot {{avgFrameSAD}(j)}} \right)} + {\sum\limits_{j = 1}^{M}\left( {W_{j} \cdot {{avgFrameSAD}(j)}} \right)} + {W_{0} \cdot {{avgFrameSAD}(0)}}} & (D)\end{matrix}$In equation (D), “avgFrameSAD” expresses (as described above) theaverage macroblock SAD (MbSAD(k, m)) value in a frame, avgFrameSAD(0) isthe avgFrameSAD for the current frame, and negative j indexes timeinstances before the current and positive j indexes time instances afterthe current frame. Hence, avgFrameSAD(j=−2) expresses the average frameSAD of two frames before the current frame, avgFrameSAD(j=3) expressesthe average frame SAD of three frames after the current frame.

Also, in equation (D), the variables N and M refer to the number offrames that are respectively before and after the current frame. Insteadof simply selecting the values N and M based on particular number offrames, some embodiments compute the values N and M based on theparticular durations of time before and after the time of the currentframe. Correlating the motion masking to temporal durations is moreadvantageous than correlating the motion masking to a set number offrames. This is because the correlation of the motion masking with thetemporal durations is directly in line with the viewer's time-basedvisual perception. The correlation of such masking with the number offrames, on the other hand, suffers from a variable display duration asdifferent displays present video at different frame rates.

In equation (D), “W” refers to a weighting factor, which, in someembodiment, decreases as the frame j gets further from the currentframe. Also, in this equation, the first summation expresses the amountof motion that can be masked before the current frame, the secondsummation expresses the amount of motion that can be masked after thecurrent frame, and the last expression (avgFrameSAD(0)) expresses theframe SAD of the current frame.

In some embodiments, the weighting factors are adjusted to account forscene changes. For instance, some embodiments account for an upcomingscene change within the look ahead range (i.e., within the M frames) butnot any frames after a scene change. For instance, these embodimentsmight set the weighting factors to zero for frames within the look aheadrange that are after a scene change. Also, some embodiments do notaccount for frames prior to or on a scene change within the look behindrange (i.e., within the N frames). For instance, these embodiments mightset the weighting factors to zero for frames within the look behindrange that relate to a previous scene or fall before the previous scenechange.

3. Variations to the Second Approach

a) Limiting the Influence of Past and Future Frames on theTemporal_Activity_Attribute

Equation (D) above essentially expresses the Temporal_Activity_Attributein the following terms:Temporal_Activity_Attribute=Past_Frame_Activity+Future_Frame_Activity+Current_Frame_Activity,where Past_Frame_Activity (PFA) equals${\sum\limits_{i = 1}^{N}\left( {W_{i} \cdot {{avgFrameSAD}(i)}} \right)},$Future_Frame_Activity (FFA) equals${\sum\limits_{j = 1}^{M}\left( {W_{j} \cdot {{avgFrameSAD}(j)}} \right)},$and Current_Frame_Activity (CFA) equals avgFrameSAD(current).

Some embodiments modify the calculation of theTemporal_Activity_Attribute so that neither the Past_Frame_Activity northe Future_Frame_Activity unduly control the value of theTemporal_Activity_Attribute. For instance, some embodiments initiallydefine PFA to equal${\sum\limits_{i = 1}^{N}\left( {W_{i} \cdot {{avgFrameSAD}(i)}} \right)},$and FFA to equal$\sum\limits_{j = 1}^{M}{\left( {W_{j} \cdot {{avgFrameSAD}(j)}} \right).}$

These embodiments then determine whether PFA is bigger than a scalartimes FFA. If so, these embodiments then set PFA equal to an upper PFAlimit value (e.g., a scalar times FFA). In addition to setting PFA equalto an upper PFA limit value, some embodiments may perform a combinationof setting FFA to zero and setting CFA to zero. Other embodiments mightset either of or both of PFA and CFA to a weighted combination of PFA,CFA, and FFA.

Analogously, after initially defining the PFA and FFA values based onthe weighted sums, some embodiments also determine whether FFA value isbigger than a scalar times PFA. If so, these embodiments then set FFAequal to an upper FFA limit value (e.g., a scalar times PFA). ). Inaddition to setting FFA equal to an upper FFA limit value, someembodiments may perform a combination of setting PFA to zero and settingCFA to zero. Other embodiments may set either of or both of FFA and CFAto a weighted combination of FFA, CFA, and PFA.

The potential subsequent adjustment of the PFA and FFA values (after theinitial computation of these values based on the weighted sums) preventeither of these values from unduly controlling theTemporal_Activity_Attribute.

b) Limiting the Influence of Spatial_Activity_Attribute andTemporal_Activity_Attribute on the Activity_Attribute

Equation (C) above essentially expresses the Activity_Attribute in thefollowing terms:Activity_Attribute=Spatial_Activity+Temporal_Activity,where the Spatial_Activity equals ascalar*(scalar*Spatial_Activity_Attribute)^(β), and Temporal_Activityequals a scalar*(scalar*Temporal_Activity_Attribute)^(Δ).

Some embodiments modify the calculation of the Activity_Attribute sothat neither the Spatial_Activity nor the Temporal_Activity undulycontrol the value of the Activity_Attribute. For instance, someembodiments initially define the Spatial_Activity (SA) to equal ascalar*(scalar*Spatial_Activity_Attribute)^(β), and define theTemporal_Activity (TA) to equal ascalar*(scalar*Temporal_Activity_Attribute)^(Δ).

These embodiments then determine whether SA is bigger than a scalartimes TA. If so, these embodiments then set SA equal to an upper SAlimit value (e.g., a scalar times TA). In addition to setting SA equalto an upper SA limit in such a case, some embodiments might also set theTA value to zero or to a weighted combination of TA and SA.

Analogously, after initially defining the SA and TA values based on theexponential equations, some embodiments also determine whether TA valueis bigger than a scalar times SA. If so, these embodiments then set TAequal to an upper TA limit value (e.g., a scalar times SA). In additionto setting TA equal to an upper TA limit in such a case, someembodiments might also set the SA value to zero or to a weightedcombination of SA and TA.

The potential subsequent adjustment of the SA and TA values (after theinitial computation of these values based on the exponential equations)prevent either of these values from unduly controlling theActivity_Attribute.

B. Computing the Macroblock-Level Masking Strength

1. First Approach

In some embodiments, the macroblock-level masking strength φ_(MB)(k, m)is calculated as follows:φ_(MB)(k, m)=A*power(C*avgMbLuma(k,m), ’)*power(B*MbSAD(k, m),α_(MB)),  (F)where

-   -   avgMbLuma(k, m) is the average pixel intensity in frame k,        macroblock m;    -   α_(MB), β, A, B, and C are constants and/or are adapted to the        local statistics.

2. Second Approach

The above-described equation (F) computes the macroblock maskingstrength essentially as follows:φ_(MB)(k,m)=D*power(E*Mb_Brightness_Attribute,exponent0)*power(scalar*Mb_(—)Spatial_Activity_Attribute, exponent1).In equation (F), the macroblock's Mb_Brightness_Attribute equalsavgMbLuma(k,m), and Mb_Spatial_Activity_Attribute equals avgMbSAD(k).This Mb_Spatial_Activity_Attribute measures the amount of spatialinnovations in a region of pixels within the macroblock that is beingcoded.

Just as in the case of the frame masking strength, some embodimentsmight expand the activity measure in the macroblock masking strength toinclude the amount of temporal innovations in a region of pixels acrossa number of successive frames. Specifically, these embodiments wouldcompute the macroblock masking strength as follows:φ_(MB)(k,m)=D*power(E*Mb_Brightness_Attribute,exponent0)*power(scalar*Mb_Activity_Attribute,exponent1),   (G)where the Mb_Activity_Attribute is given by the following equation (H),Mb_Activity_Attribute=F*power(D*Mb_Spatial_Activity_Attribute,exponent_beta)+G*power(F*Mb_Temporal_Activity_Attribue, exponent_delta)  (H)

The computation of the Mb_Temporal_Activity_Attribute for a macroblockcan be analogous to the above-described computation of theMb_Temporal_Activity_Attribute for a frame. For instance, in some ofthese embodiments, the Mb Temporal_Activity_Attribute is provided by theequation (I) below:

Mb_Temporal_Activity_Attribute= $\begin{matrix}{{\sum\limits_{i = 1}^{N}\left( {W_{i} \cdot {{MbSAD}\left( {i,m} \right)}} \right)} + {\sum\limits_{j = 1}^{M}\left( {W_{j} \cdot {{MbSAD}\left( {j,m} \right)}} \right)} + {{MbSAD}(m)}} & (I)\end{matrix}$The variables in the equation (I) were defined in Section III.A. Inequation (F), the macroblock m in frame i or j can be the macroblock inthe same location as the macroblock m in the current frame, or can bethe macroblock in frame i or j that is initially predicted to correspondthe macroblock m in the current frame.

The Mb_Temporal_Activity_Attribute provided by equation (I) can bemodified in an analogous manner to the modifications (discussed inSection III.A.3 above) of the frame Temporal_Activity_Attribute providedby equation (D). Specifically, the Mb_Temporal_Activity_Attributeprovided by the equation (I) can be modified to limit the undueinfluence of macroblocks in the past and future frames.

Similarly, the Mb_Activity_Attribute provided by equation (H) can bemodified in an analogous manner to the modifications (discussed inSection III.A.3 above) of the frame Activity_Attribute provided byequation (C). Specifically, the Mb_Activity_Attribute provided byequation (H) can be modified to limit the undue influence of theMb_Spatial_Activity_Attribute and the Mb_Temporal_Activity_Attribute.

C. Computing the Masked QP Values

Based on the values of masking strengths (φ_(F) and φ_(MB)) and thevalue of the reference masking strength (φ_(R)), the visual maskingprocess can calculate the masked QP values at the frame level andmacroblock level by using two functions CalcMQP and CalcMQPforMB. Thepseudo code for these two functions is below:  CalcMQP(nominalQP, φ_(R),φ_(F)(k), maxQPFrameAdjustment)  {   QPFrameAdjustment = β _(F)*(φ_(F)(k) − φ_(R)) / φ_(R);   clip QPFrameAdjustment to lie within[minQPFrameAdjustment,,  maxQPFrameAdjustment];   maskedQPofFrame =nominalQP + QPFrameAdjustment;   clip maskedQPofFrame to lie in theadmissible range;   return maskedQPofFrame (for frame k);  } CalcMQPforMB(maskedQPofFrame, φ_(F)(k), φ_(MB)(k, m),maxQPMacroblockAdjustment)  {   if (φ_(F)(k) >T)  where T is a suitablychosen threshold      QPMacroblockAdjustment= β _(MB) * (φ_(MB)(k, m) −φ_(F)(k)) /    φ_(F)(k);   else      QPMacroblockAdjustment= 0;   clipQPMacroblockAdjustment so that it lies within[minQPMacroblockAdjustment, maxQPMacroblockAdjustment ];  maskedQPofMacroblock = maskedQPofFrame +  QPMacroblockAdjustment;  clip maskedQPofMacroblock so that it lies within the valid QP value range;   return maskedQPofMacroblock;  }

In the above functions, β_(F) and β_(MB) can be predetermined constantsor adapted to local statistics.

IV. MULTI-PASS ENCODING

FIG. 1 presents a process 100 that conceptually illustrates themulti-pass encoding method of some embodiments of the invention. Asshown in this figure, the process 100 has three stages, which aredescribed in the following three sub-sections.

A. Analysis and initial QP selection As shown in FIG. 1, the process 100initially computes (at 105) the initial value of the reference maskingstrength (φ_(R(1))) and the initial value of the nominal quantizationparameter (QP_(Nom(1))) during the initial analysis stage (i.e., duringpass 0) of the multi-pass encoding process. The initial referencemasking strength (φ_(R(1))) is used during the first search stage, whilethe initial nominal quantization parameter (QP_(Nom(1))) is used duringthe first pass of the first search stage (i.e., during pass 1 of themulti-pass encoding process).

At the beginning of pass 0, φ_(R(0)) can be some arbitrary value or avalue selected based on experimental results (for instance, the middlevalue of a typical range of φ_(R) values). During an analysis of thesequence, a masking strength φ_(F)(k) is computed for each frame, thenthe reference masking strength, φ_(R(1)), is set to be equal toavg(φ_(F)(k)) at the end of pass 0. Other decisions for the referencemasking strength φ_(R) are also possible. For instance, it may becomputed as the median or other arithmetic function of the valuesφ_(F)(k), e.g., a weighted average of the values φ_(F)(k).

There are several approaches to initial QP selection with varyingcomplexity. For instance, the initial nominal QP can be selected as anarbitrary value (e.g., 26). Alternatively, a value can be selected thatis known to produce an acceptable quality for the target bit rate basedon coding experiments.

The initial nominal QP value can also be selected from a look-up tablebased on spatial resolution, frame rate, spatial/temporal complexity,and target bit rate. In some embodiments, this initial nominal QP valueis selected from the table using a distance measure that depends on eachof these parameters, or it may be selected using a weighted distancemeasure of these parameters.

This initial nominal QP value can also be set to the adjusted average ofthe frame QP values as they are selected during a fast encoding with arate controller (without masking), where the average has been adjustedbased on the bit rate percentage rate error E₀ for pass 0. Similarly,the initial nominal QP can also be set to a weighted adjusted average ofthe frame QP values, where the weight for each frame is determined bythe percentage of macroblocks in this frame that are not coded asskipped macroblocks. Alternatively, the initial nominal QP can be set toan adjusted average or an adjusted weighted average of the frame QPvalues as they are selected during a fast encoding with a ratecontroller (with masking), as long as the effect of changing thereference masking strength from φ_(R(0)) to φ_(R(1)) is taken intoaccount.

B. First Search Stage: Nominal QP Adjustments

After 105, the multi-pass encoding process 100 enters the first searchstage. In first search stage, the process 100 performs N₁ encodings ofthe sequence, where N₁ represents the number of passes through the firstsearch stage. During each pass of the first stage, the process uses achanging nominal quantization parameter with a constant referencemasking strength.

Specifically, during each pass p in the first search stage, the process100 computes (at 107) a particular quantization parameter MQP_(p)(k) foreach frame k and a particular quantization parameter MQP_(MB(p))(k, m)for each individual macroblock m within the frame k. The calculation ofthe parameters MQP_(p)(k) and MQP_(MB(p))(k, m) for a given nominalquantization parameter QP_(Nom(p)) and reference masking strengthφ_(R(p)) was described in Section III (where MQP_(p)(k) andMQP_(MB(p))(k, m) are computed by using the functions CalcMQP andCalcMQPforMB, which were described above in Section III). In the firstpass (i.e., pass 1) through 107, the nominal quantization parameter andthe first-stage reference masking strength are parameter QP_(Nom(1)) andreference masking strength φ_(R(1)), which were computed during theinitial analysis stage 105.

After 107, the process encodes (at 110) the sequence based on thequantization parameter values computed at 107. Next, the encodingprocess 100 determines (at 115) whether it should terminate. Differentembodiments have different criteria for terminating the overall encodingprocess. Examples of exit conditions that completely terminate themulti-pass encoding process include:

-   -   |E_(p)|<ε, where ε is the error tolerance in the final bit rate.    -   QP_(Nom(p)) is at the upper or lower bound of the valid range of        QP values.    -   The number of passes has exceeded the maximum number of        allowable passes P_(MAX).        Some embodiments might use all of these exit conditions, while        other embodiments might only use some of them. Yet other        embodiments might use other exit conditions for terminating the        encoding process.

When the multi-pass encoding process decides (at 115) to terminate, theprocess 100 omits the second search stage and transitions to 145. At145, the process saves the bitstream from the last pass p as the finalresult, and then terminates.

On the other hand, when the process determines (at 115) that it shouldnot terminate, it then determines (at 120) whether it should terminatethe first search stage. Again, different embodiments have differentcriteria for terminating the first search stage. Examples of exitconditions that terminate the first search stage of the multi-passencoding process include:

-   -   QP_(Nom(p+1)) is the same as QP_(Nom(q)), and q≦p, (in this        case, the error in bit rate cannot be lowered any further by        modifying the nominal QP).    -   |E_(p)|<ε_(C), ε_(C)>ε, where ε_(C) is the error tolerance in        the bit rate for the first search stage.    -   The number of passes has exceeded P₁, where P₁ is less than        P_(MAX).    -   The number of passes has exceeded P₂, which is less than P₁, and        |E_(p)|<ε₂, ε₂>ε_(C).        Some embodiments might use all these exit conditions, while        other embodiments might only use some of them. Yet other        embodiments might use other exit conditions for terminating the        first search stage.

When the multi-pass encoding process decides (at 120) to terminate thefirst search stage, the process 100 proceeds to the second search stage,which is described in the next sub-section. On the other hand, when theprocess determines (at 120) that it should not terminate the firstsearch stage, it updates (at 125) the nominal QP for the next pass inthe first search stage (i.e., defines QP_(Nom(p+1))). In someembodiments, the nominal QP_(Nom(p+1)) is updated as follows. At the endof pass 1, these embodiments defineQP _(Nom(p+1)) =QP _(Nom(p)) +χE _(p),where χ is a constant. At the end of each pass from pass 2 to pass N₁,these embodiments then defineQP _(Nom(p+1))=InterpExtrap(0, E _(q1) , E _(q2) , QP _(Nom(q1)) , QP_(Nom(q2))),where InterpExtrap is a function that is further described below. Also,in the above equation, q1 and q2 are pass numbers with corresponding bitrate errors that are the lowest among all passes up to pass p, and q1,q2, and p have the following relationship:1≦q1≦q2<p.

Below is the pseudo code for the InterpExtrap function. Note that if xis not between x1 and x2, this function is an extrapolation function.Otherwise, it is an interpolation function. InterpExtrap(x, x1, x2, y1,y2) {   if (x2 != x1) y = y1 + (x − x1) * (y2 − y1)/(x2 − x1);   else y= y1;   return y; }The nominal QP value is typically rounded to an integer value andclipped to lie within the valid range of QP values. One of ordinaryskill in art will realize that other embodiments might compute thenominal QP_(Nom(p+1)) value differently than the approached describedabove.

After 125, the process transitions back to 107 to start the next pass(i.e., p:=p+1), and for this pass, compute (at 107) a particularquantization parameter MQP_(p)(k) for each frame k and a particularquantization parameter MQP_(MB(p))(k, m) for each individual macroblockm within the frame k for the current pass p. Next, the process encodes(at 110) the sequence of frames based on these newly computedquantization parameters. From 110, the process then transitions to 115,which was described above.

C. Second Search Stage: Reference Masking Strength Adjustments

When the process 100 determines (at 120) that it should terminate thefirst search stage, it transitions to 130. In the second search stage,the process 100 performs N₂ encodings of the sequence, where N₂represents the number of passes through the second search stage. Duringeach pass, the process uses the same nominal quantization parameter anda changing reference masking strength.

At 130, the process 100 computes a reference masking strength φ_(R(p+1))for the next pass, i.e., pass p+1, which is pass N₁+1. In pass N₁+1, theprocess 100 encodes the sequence of frames in 135. Different embodimentscompute (at 130) the reference masking strength φ_(R(p+1)) at the end ofa pass p in different ways. Two alternative approaches are describedbelow.

Some embodiments compute the reference masking strength φ_(R(p)) basedon the error in bit rate(s) and value(s) of φ_(R) from previouspass(es). For instance, at the end of pass N₁, some embodiments defineφ_(R(N1+1))=φ_(R(N1))+φ_(R(N1))×Konst×E _(N1).At the end of pass N₁+m, where m is an integer greater than 1, someembodiments defineφ_(R(N1+m))=InterpExtrap(0, E _(N1+m−2) , E _(N1+m−1), φ_(R(N1+m−2)),φ_(R(N1+m−1))).Alternatively, some embodiments defineφ_(R(N1+m))=InterpExtrap(0, E _(N1+m−q2) , E _(N1+m−q1), φ_(R(N1+m−q2)),φ_(R(N1+m−q1))),where q1 and q2 are previous passes that gave the best errors.

Other embodiments compute the reference masking strength at the end ofeach pass in the second search stage by using AMQP, which was defined inSection I. One way for computing AMQP for a given nominal QP and somevalue for φ_(R) will be described below by reference to the pseudo codeof a function GetAvgMaskedQP. GetAvgMaskedQP(nominalQP, φ_(R)) {  sum=0;   for(k=0;k<numframes;k++) {    MQP(k) = maskedQP for frame k calculated using   CalcMQP(nominalQP,φ_(R), φ_(F)(k), maxQPFrameAdjustment); // see   above     sum +=MQP(k);   }   return sum/numframes; }

Some embodiments that use AMQP, compute a desired AMQP for pass p+1based on the error in bit rate(s) and value(s) of AMQP from previouspass(es). The φ_(R(p+1)) corresponding to this AMQP is then foundthrough a search procedure given by a function Search(AMQP_((p+1)),φ_(R(p))), the pseudo code of which is given at the end of thissubsection.

For instance, some embodiments at the end of pass N₁ computeAMQP_(N1+1), whereAMQP _(N1+1)=InterpExtrap(0, E _(N1−1) , E _(N1) , AMQP _(N1−1) , AMQP_(N1)), when N ₁>1, andAMQP _(N1+1) =AMQP _(N1,) when N ₁=1,

These embodiments then define:φ_(R(N1+1))=Search(AMQP _(N1+1), φ_(R(N1)))

At the end of pass N₁+m (where m is an integer greater than 1), someembodiments define:AMQP _(N1+m)=InterpExtrap(0, E _(N1+m−2) , E _(N1+m−1) , AMQP _(N1+m−2), AMQP _(N1+m−1)), andφ_(R(N1+m))=Search(AMQP _(N1+m), φ_(R(N1+m−1)))

Given the desired AMQP and some default value of φ_(R), the φ_(R)corresponding to the desired AMQP can be found using the Searchfunction, which has the following pseudo code in some embodiments:Search(AMQP, φ_(R)) {   interpolateSuccess=True;  //until set otherwise  refLumaSad0=refLumaSad1=refLumaSadx=φ_(R);   errorInAvgMaskedQp =GetAvgMaskedQp(nominalQp, refLumaSadx) − AMQP;  if(errorInAvgMaskedQp>0){     ntimes=0;     do{       ntimes++;      refLumaSad0 = (refLumaSad0 * 1.1);       errorInAvgMaskedQp =GetAvgMaskedQp(nominalQp,refLumaSad0) −       amqp;    }while(errorInAvgMaskedQp>0 && ntimes<10);    if(ntimes>=10)interpolateSuccess=False;   }   else{//errorInAvgMaskedQp<0     ntimes=0;     do{       ntimes++;      refLumaSad1 = (refLumaSad1 * 0.9);       errorInAvgMaskedQp =GetAvgMaskedQp(nominalQp,refLumaSad1) −       amqp;    }while(errorInAvgMaskedQp<0 && ntimes<10);    if(ntimes>=10)interpolateSuccess=False;   }   ntimes=0;   do{    ntimes++;     refLumaSadx = (refLumaSad0+refLumaSad1)/2; //simplesuccessive     approximation     errorInAvgMaskedQp =GetAvgMaskedQp(nominalQp,refLumaSadx) − AMQP;    if(errorInAvgMaskedQp>0)refLumaSad1=refLumaSadx;     elserefLumaSad0=refLumaSadx;   }while( ABS (errorInAvgMaskedQp) > 0.05 &&ntimes<12 );   if(ntimes>=12)interpolateSuccess=False;   }   if(interpolateSuccess) return refLumaSadx;   else return φ_(R); }

In the above pseudo code, the numbers 10, 12 and 0.05 may be replacedwith suitably chosen thresholds.

After computing the reference masking strength for the next pass (passp+1) through the encoding of the frame sequence, the process 100transitions to 132 and starts the next pass (i.e., p:=p+1). For eachframe k and each macroblock m during each encoding pass p, the processcomputes (at 132) a particular quantization parameter MQP_(p)(k) foreach frame k and particular quantization parameters MQP_(MB(p))(k, m)for individual macroblocks m within the frame k. The calculation of theparameters MQP_(p)(k) and MQP_(MB(p))(k, m) for a given nominalquantization parameter QP_(Nom(p)) and reference masking strengthφ_(R(p)), were described in Section III (where MQP_(p)(k) andMQP_(MB(p))(k, m) are computed by using the functions CalcMQP andCalcMQPforMB, which were described above in Section III). During thefirst pass through 132, the reference masking strength is the one thatwas just computed at 130. Also, during the second search stage, thenominal QP remains constant throughout the second search stage. In someembodiments, the nominal QP through the second search stage is thenominal QP that resulted in the best encoding solution (i.e., in theencoding solution with the lowest bit rate error) during the firstsearch stage.

After 132, the process encodes (at 135) the frame sequence using thequantization parameters computed at 130. After 135, the processdetermines (at 140) whether it should terminate the second search stage.Different embodiments use different criteria for terminating the secondsearch stage at the end of a pass p. Examples of such criteria are:

-   -   |E_(p)|<ε, where ε is the error tolerance in the final bit rate    -   The number of passes has exceeded the maximum number of passes        allowed        Some embodiments might use all of these exit conditions, while        other embodiments might only use some of them. Yet other        embodiments might use other exit conditions for terminating the        first search stage.

When the process 100 determines (at 140) that it should not terminatethe second search stage, it returns to 130 to recompute the referencemasking strength for the next pass of encoding. From 130, the processtransitions to 132 to compute quantization parameters and then to 135 toencode the video sequence by using the newly computed quantizationparameters.

On the other hand, when the process decides (at 140) to terminate thesecond search stage, it transitions to 145. At 145, the process 100saves the bitstream from the last pass p as the final result, and thenterminates.

V. DECODER INPUT BUFFER UNDERFLOW CONTROL

Some embodiments of the invention provide a multi-pass encoding processthat examines various encodings of a video sequence for a target bitrate, in order to identify an optimal encoding solution with respect tothe usage of an input buffer used by the decoder. In some embodiment,this multi-pass process follows the multi-pass encoding process 100 ofFIG. 1.

The decoder input buffer (“decoder buffer”) usage will fluctuate to somedegree during the decoding of an encoded sequence of images (e.g.,frames), because of a variety of factors, such as fluctuation in thesize of encoded images, the speed with which the decoder receivesencoded data, the size of the decoder buffer, the speed of the decodingprocess, etc.

A decoder buffer underflow signifies the situation where the decoder isready to decode the next image before that image has completely arrivedat the decoder side. The multi-pass encoder of some embodimentssimulates the decoder buffer and re-encode selected segments in thesequence to prevent decoder buffer underflow.

FIG. 2 conceptually illustrates a codec system 200 of some embodimentsof the invention. This system includes a decoder 205 and an encoder 210.In this figure, the encoder 210 has several components that enable it tosimulate the operations of similar components of the decoder 205.

Specifically, the decoder 205 has an input buffer 215, a decodingprocess 220, and an output buffer 225. The encoder 210 simulates thesemodules by maintaining a simulated decoder input buffer 230, a simulateddecoding process 235, and a simulated decoder output buffer 240. Inorder not to obstruct the description of the invention, FIG. 2 issimplified to show the decoding process 220 and encoding process 245 assingle blocks. Also, in some embodiments, the simulated decoding process235 and simulated decoder output buffer 240 are not utilized for bufferunderflow management, and are therefore shown in this figure forillustration only.

The decoder maintains the input buffer 215 to smooth out variations inthe rate and arrival time of incoming encoded images. If the decoderruns out of data (underflow) or fills up the input buffer (overflow),there will be visible decoding discontinuities as the picture decodinghalts or incoming data is discarded. Both of these cases areundesirable.

To eliminate the underflow condition, the encoder 210 in someembodiments first encodes a sequence of images and stores them in astorage 255. For instance, the encoder 210 uses the multi-pass encodingprocess 100 to obtain a first encoding of the sequence of images. Itthen simulates the decoder input buffer 215 and re-encodes the imagesthat would cause buffer underflow. After all buffer underflow conditionsare removed, the re-encoded images are supplied to the decoder 205through a connection 255, which maybe a network connection (Internet,cable, PSTN lines, etc.), a non-network direct connection, a media (DVD,etc.), etc.

FIG. 3 illustrates an encoding process 300 of the encoder of someembodiments. This process tries to find an optimal encoding solutionthat does not cause the decoder buffer to underflow. As shown in FIG. 3,the process 300 identifies (at 302) a first encoding of the sequence ofimages that meets a desired target bit rate (e.g., the average bit ratefor each image in the sequence meets a desired average target bit rate).For instance, the process 300 may use (at 302) the multi-pass encodingprocess 100 to obtain the first encoding of the sequence of images.

After 302, the encoding process 300 simulates (at 305) the decoder inputbuffer 215 by considering a variety of factors, such as the connectionspeed (i.e., the speed with which the decoder receives encoded data),the size of the decoder input buffer, the size of encoded images, thedecoding process speed, etc. At 310, the process 300 determines if anysegment of the encoded images will cause a decoder input buffer tounderflow. The techniques that the encoder uses to determine (andsubsequently eliminate) the underflow condition are described furtherbelow.

If the process 300 determines (at 310) that the encoded images do notcreate underflow condition, the process ends. On the other hand, if theprocess 300 determines (at 310) that a buffer underflow condition existsin any segment of the encoded images, it refines (at 315) the encodingparameters based on the value of these parameters from previous encodingpasses. The process then re-encodes (at 320) the segment with underflowto reduce the segment bit size. After re-encoding the segment, theprocess 300 examines (at 325) the segment to determine if the underflowcondition is eliminated.

When the process determines (at 325) that the segment still causesunderflow, the process 300 transitions to 315 to further refine theencoding parameters to eliminate underflow. Alternatively, when theprocess determines (at 325) that the segment will not cause anyunderflow, the process specifies (at 330) that starting point forre-examining and re-encoding the video sequence as the frame after theend of the segment re-encoded in the last iteration at 320. Next, at335, the process re-encodes the portion of the video sequence specifiedat 330, up to (and excluding) the first IDR frame following theunderflow segment specified at 315 and 320. After 335, the processtransitions back to 305 to simulate the decoder buffer to determinewhether the rest of the video sequence still causes buffer underflowafter re-encoding. The flow of the process 300 from 305 was describedabove.

A. Determining the Underflow Segment in the Sequence of Encoded Images

As described above, the encoder simulates the decoder buffer conditionsto determine whether any segment in the sequence of the encoded orre-encoded images cause underflow in the decoder buffer. In someembodiments, the encoder uses a simulation model that considers the sizeof encoded images, network conditions such as bandwidth, decoder factors(e.g., input buffer size, initial and nominal time to remove images,decoding process time, display time of each image, etc.).

In some embodiments, the MPEG-4 AVC Coded Picture Buffer (CPB) model isused to simulate the decoder input buffer conditions. The CPB is theterm used in MPEG-4 H.264 standard to refer to the simulated inputbuffer of the Hypothetical Reference Decoder (HRD). The HRD is ahypothetical decoder model that specifies constraints on the variabilityof conforming streams that an encoding process may produce. The CPBmodel is well known and is described in Section 1 below for convenience.More detailed description of CPB and HRD can be found in Draft ITU-TRecommendation and Final Draft International Standard of Joint VideoSpecification (ITU-T Rec. H.264/ISO/IEC 14496-10 AVC).

1. Using the CPB Model to Simulate the Decoder Buffer

The following paragraphs describe how the decoder input buffer issimulated in some embodiments using the CPB model. The time at which thefirst bit of image n begins to enter the CPB is referred to as theinitial arrival time t_(ai)(n), which is derived as follows:

-   -   t_(ai)(0)=0, when the image is the first image (i.e., image 0),    -   t_(ai)(n)=Max(t_(af)(n−1), t_(ai,earliest)(n) ), when the image        is not the first image in the sequence being encoded or        re-encoded (i.e., where n>0).        In the above equation,    -   t_(ai,earliest)(n)=t_(r,n)(n)−initial_cpb_removal_delay,        where t_(r,n)(n) is the nominal removal time of image n from the        CPB as specified below and initial_cpb_removal_delay is the        initial buffering period.

The final arrival time for image n is derived byt _(af)(n)=t _(ai)(n)+b(n)/BitRate,where b(n) is the size in bits of image n.

In some embodiments, the encoder makes its own calculations of thenominal removal time as described below instead of reading them from anoptional part of the bit stream as in the H.264 specification. For image0, the nominal removal time of the image from the CPB is specified byt _(r,n)(0)=initial_(—) cpb_removal_delayFor image n (n>0), the nominal removal time of the image from the CPB isspecified byt _(r,n)(n)=t _(r,n)(0)+sum_(i=0 to n−1)(t _(i))where t_(r,n)(n) is the nominal removal time of image n, and t_(i) isthe display duration for picture i.

The removal time of image n is specified as follows.t _(r)(n)=t _(r,n)(n), when t _(r,n)(n)>=t _(af)(n),t _(r)(n)=t _(af)(n) when t _(r,n)(n)<t _(af)(n)

It is this latter case that indicates that the size of image n, b(n), isso large that it prevents removal at the nominal removal time.

2. Detection of Underflow Segments

As described in the previous section, the encoder can simulate thedecoder input buffer state and obtain the number of bits in the bufferat a given time instant. Alternatively, the encoder can track how eachindividual image changes the decoder input buffer state via thedifference between its nominal removal time and final arrival time(i.e., t_(b)(n)=t_(r,n)(n)−t_(af)(n)). When t_(b)(n) is less than 0, thebuffer is suffering from underflow between time instants t_(r,n)(n) andt_(af)(n), and possibly before t_(r,n)(n) and after t_(af)(n).

The images directly involved in an underflow can be easily found bytesting whether t_(b)(n) is less than 0. However, the images witht_(b)(n) less than 0 do not necessarily cause an underflow, andconversely the images causing an underflow might not have t_(b)(n) lessthan 0. Some embodiments define an underflow segment as a stretch ofconsecutive images (in decoding order) that cause underflow bycontinuously depleting the decoder input buffer until underflow reachesits worst point.

FIG. 4 is a plot of the difference between nominal removal time andfinal arrival of images t_(b)(n) versus image number in someembodiments. The plot is drawn for a sequence of 1500 encoded images.FIG. 4 a shows an underflow segment with arrows marking its beginningand end. Note that there is another underflow segment in FIG. 4 a thatoccurs after the first underflow segment, which is not explicitly markedby arrows for simplicity.

FIG. 5 illustrates a process 500 that the encoder uses to perform theunderflow detection operation at 305. The process 500 first determines(at 505) the final arrival time, t_(af), and nominal removal time,t_(r,n), of each image by simulating the decoder input buffer conditionsas explained above. Note that since this process may be called severaltimes during the iterative process of buffer underflow management, itreceives an image number as the starting point and examines the sequenceof images from this given starting image. Obviously, for the firstiteration, the starting point is the first image in the sequence.

At 510, the process 500 compares the final arrival time of each image atthe decoder input buffer with the nominal removal time of that image bythe decoder. If the process determines that there are no images withfinal arrival time after the nominal removal time (i.e., no underflowcondition exits), the process exits. On the other hand, when an image isfound for which the final arrival time is after the nominal removaltime, the process determines that there is an underflow and transitionsto 515 to identify the underflow segment.

At 515, the process 500 identifies the underflow segment as the segmentof the images where the decoder buffer starts to be continuouslydepleted until the next global minimum where the underflow conditionstarts to improve (i.e., t_(b)(n) does not get more negative over astretch of images). The process 500 then exits. In some embodiments, thebeginning of the underflow segment is further adjusted to start with anI-frame, which is an intra-encoded image that marks the starting of aset of related inter-encoded images. Once one or more segments that arecausing the underflow are identified, the encoder proceeds to eliminatethe underflow. Section B below describes elimination of underflow in asingle-segment case (i.e., when the entire sequence of encoded imagesonly contains a single underflow segment). Section C then describeselimination of underflow for the multi-segment underflow cases.

B. Single-Segment Underflow Elimination

Referring to FIG. 4(a), if the t_(b)(n)-versus-n curve only crosses then-axis once with a descending slope, then there is only one underflowsegment in the entire sequence. The underflow segment begins at thenearest local maximum preceding the zero-crossing point, and ends at thenext global minimum between the zero-crossing point and the end of thesequence. The end point of the segment could be followed by anotherzero-crossing point with the curve taking an ascending slope if thebuffer recovers from the underflow.

FIG. 6 illustrates a process 600 the encoder utilizes (at 315, 320, and325) to eliminate underflow condition in a single segment of images insome embodiments. At 605, the process 600 estimates the total number ofbits to reduce (ΔB) in the underflow segment by computing the product ofthe input bit rate into the buffer and the longest delay (e.g., minimumt_(b)(n)) found at the end of the segment.

Next, at 610, the process 600 uses the average masked frame QP (AMQP)and total number of bits in the current segment from the last encodingpass (or passes) to estimate a desired AMQP for achieving a desirednumber of bits for the segment, B_(T)=B−ΔB_(p), where p is the currentnumber of iterations of the process 600 for the segment. If thisiteration is the first iteration of process 600 for the particularsegment, AMQP and total number of bits are the AMQP and the total numberof bits for this segment that are derived from the initial encodingsolution identified at 302. On the other hand, when this iteration isnot the first iteration of process 600, these parameters can be derivedfrom the encoding solution or solutions obtained in the last pass orlast several passes of the process 600.

Next, at 615, the process 600 uses the desired AMQP to modify averagemasked frame QP, MQP(n), based on masking strength φ_(F)(n) such thatimages that can tolerate more masking get more bit reductions. Theprocess then re-encodes (at 620) the video segment based on theparameters defined at 315. The process then examines (at 625) thesegment to determine whether the underflow condition is eliminated. FIG.4(b) illustrates the elimination of the underflow condition of FIG. 4(a)after process 600 is applied to the underflow segment to re-encode it.When the underflow condition is eliminated, the process exits.Otherwise, it will transition back to 605 to further adjust encodingparameters to reduce total bit size.

C. Underflow Elimination with Multiple Underflow Segments

When there are multiple underflow segments in a sequence, re-encoding ofa segment changes the buffer fullness time, t_(b)(n), for all theensuing frames. To account for the modified buffer condition, theencoder searches for one underflow segment at a time, starting from thefirst zero-crossing point (i.e., at the lowest n) with a descendingslope.

The underflow segment begins at the nearest local maximum preceding thiszero-crossing point, and ends at the next global minimum between thezero-crossing point and the next zero-crossing point (or the end of thesequence if there is no more zero crossing). After finding one segment,the encoder hypothetically removes the underflow in this segment andestimates the updated buffer fullness by setting t_(b)(n) to 0 at theend of the segment and redoing the buffer simulation for all subsequentframes.

The encoder then continues searching for the next segment using themodified buffer fullness. Once all underflow segments are identified asdescribed above, the encoder derives the AMQPs and modifies the Maskedframe QPs for each segment independently of the others just as in thesingle-segment case.

One of ordinary skill would realize that other embodiments might beimplemented differently. For instance, some embodiments would notidentify multiple segments that cause underflow of the input buffer ofthe decoder. Instead, some embodiments would perform buffer simulationas described above to identify a first segment that causes underflow.After identifying such a segment, these embodiments correct the segmentto rectify underflow condition in that segment and then resume encodingfollowing the corrected portion. After the encoding of the remaining ofthe sequence, these embodiments will repeat this process for the nextunderflow segment.

D. Applications of Buffer Underflow Management

The decoder buffer underflow techniques described above applies tonumerous encoding and decoding systems. Several examples of such systemsare described below.

FIG. 7 illustrates a network 705 connecting a video streaming server 710and several client decoders 715-725. Clients are connected to thenetwork 705 via links with different bandwidths such as 300 Kb/sec and 3Mb/sec. The video streaming server 710 is controlling streaming ofencoded video images from an encoder 730 to the client decoders 715-725.

The streaming video server may decide to stream the encoded video imagesusing the slowest bandwidth in the network (i.e., 300 Kb/sec) and thesmallest client buffer size. In this case, the streaming server 710needs only one set of encoded images that are optimized for a target bitrate of 300 Kb/sec. On the other hand, the server may generate and storedifferent encodings that are optimized for different bandwidths anddifferent client buffer conditions.

FIG. 8 illustrates another example of an application for decoderunderflow management. In this example, an HD-DVD player 805 is receivingencoded video images from an HD-DVD 840 that has stored encoded videodata from a video encoder 810. The HD-DVD player 805 has an input buffer815, a set of decoding modules shown as one block 820 for simplicity,and an output buffer 825.

The output of the player 805 is sent to display devices such as TV 830or computer display terminal 835. The HD-DVD player may have a very highbandwidth, e.g. 29.4 Mb/sec. In order to maintain a high quality imageon the display devices, the encoder ensures that the video images areencoded in a way that no segments in the sequence of images would be solarge that cannot be delivered to the decoder input buffer on time.

VI. COMPUTER SYSTEM

FIG. 9 presents a computer system with which one embodiment of theinvention is implemented. Computer system 900 includes a bus 905, aprocessor 910, a system memory 915, a read-only memory 920, a permanentstorage device 925, input devices 930, and output devices 935. The bus905 collectively represents all system, peripheral, and chipset busesthat communicatively connect the numerous internal devices of thecomputer system 900. For instance, the bus 905 communicatively connectsthe processor 910 with the read-only memory 920, the system memory 915,and the permanent storage device 925.

From these various memory units, the processor 910 retrievesinstructions to execute and data to process in order to execute theprocesses of the invention. The read-only-memory (ROM) 920 stores staticdata and instructions that are needed by the processor 910 and othermodules of the computer system.

The permanent storage device 925, on the other hand, is read-and-writememory device. This device is a non-volatile memory unit that storesinstruction and data even when the computer system 900 is off. Someembodiments of the invention use a mass-storage device (such as amagnetic or optical disk and its corresponding disk drive) as thepermanent storage device 925.

Other embodiments use a removable storage device (such as a floppy diskor zips® disk, and its corresponding disk drive) as the permanentstorage device. Like the permanent storage device 925, the system memory915 is a read-and-write memory device. However, unlike storage device925, the system memory is a volatile read-and-write memory, such as arandom access memory. The system memory stores some of the instructionsand data that the processor needs at runtime. In some embodiments, theinvention's processes are stored in the system memory 915, the permanentstorage device 925, and/or the read-only memory 920.

The bus 905 also connects to the input and output devices 930 and 935.The input devices enable the user to communicate information and selectcommands to the computer system. The input devices 930 includealphanumeric keyboards and cursor-controllers. The output devices 935display images generated by the computer system. The output devicesinclude printers and display devices, such as cathode ray tubes (CRT) orliquid crystal displays (LCD).

Finally, as shown in FIG. 9, bus 905 also couples computer 900 to anetwork 965 through a network adapter (not shown). In this manner, thecomputer can be a part of a network of computers (such as a local areanetwork (“LAN”), a wide area network (“WAN”), or an Intranet) or anetwork of networks (such as the Internet). Any or all of the componentsof computer system 900 may be used in conjunction with the invention.However, one of ordinary skill in the art would appreciate that anyother system configuration may also be used in conjunction with thepresent invention.

While the invention has been described with reference to numerousspecific details, one of ordinary skill in the art will recognize thatthe invention can be embodied in other specific forms without departingfrom the spirit of the invention. For instance, instead of using H264method of simulating the decoder input buffer other simulation methodsmay be used that consider the buffer size, arrival and removal times ofimages in the buffer, and decoding and display times of the images.

Several embodiments described above compute the mean removed SAD toobtain an indication of the image variance in a macroblock. Otherembodiments, however, might identify the image variance differently. Forexample, some embodiments might predict an expected image value for thepixels of a macroblock. These embodiments then generate a macroblock SADby subtracting this predicted value form the luminance value of thepixels of the macroblock, and summing the absolute value of thesubtractions. In some embodiments, the predicted value is based on notonly the values of the pixels in the macroblock but also the value ofthe pixels in one or more of the neighboring macroblocks.

Also, the embodiments described above use the derived spatial andtemporal masking values directly. Other embodiments will apply asmoothing filtering on sucessive spatial masking values and/or tosuccessive temporal masking values before using them in order to pickout the general trend of those values through the video images. Thus,one of ordinary skill in the art would understand that the invention isnot to be limited by the foregoing illustrative details.

1. A method of encoding of a plurality of images in a video sequence,the method comprising: a) iteratively performing an encoding operationthat encodes the images, wherein each encoding operation is based on anominal quantization parameter, said nominal quantization parameter usedto define quantization parameters for the images, wherein the nominalquantization parameters are different during a plurality of differentiterations of the encoding operation; and b) stopping the iterationswhen an encoding operation satisfies a set of termination criteria. 2.The method of claim 1, wherein the set of termination criteria includesthe identification of an acceptable encoding of the images.
 3. Themethod of claim 2, wherein an acceptable encoding of the images is anencoding of the images that is within a particular range of a target bitrate.
 4. A method of encoding a plurality of images, the methodcomprising: a) defining a nominal quantization parameter for encodingthe images; b) deriving at least an image-specific quantizationparameter for at least one image based on the nominal quantizationparameter; c) encoding the images based on the image-specificquantization parameter; and d) iteratively repeating the defining,deriving, and encoding operations to optimize the encoding.
 5. Themethod of claim 4 further comprising: a) deriving a plurality ofimage-specific quantization parameters for a plurality of images basedon the nominal quantization parameter; b) encoding the images based onthe image-specific quantization parameters; and c) repeating thedefining, deriving, and encoding operations to optimize the encoding. 6.The method of claim 4 further comprising stopping the iterations when anencoding operation satisfies a set of termination criteria.
 7. Themethod of claim 6, wherein the set of termination criteria includes theidentification of an acceptable encoding of the images.
 8. The method ofclaim 7, wherein an acceptable encoding of the images is an encoding ofthe images that is within a particular range of a target bit rate.
 9. Amethod of encoding a plurality of images, the method comprising: a)identifying a plurality of image attributes for a plurality of images,each particular image attribute quantifying the complexity of at least aparticular portion of a particular image, b) identifying a referenceattribute that quantifies the complexity of the plurality of images, c)identifying quantization parameters for encoding the plurality of imagesbased on the identified attributes; d) encoding the plurality of imagesbased on the identified quantization parameter; and e) iterativelyperforming the identifying and encoding operations to optimize theencoding, wherein a plurality of different iterations use a plurality ofdifferent reference attributes.
 10. The method of claim 9, wherein aplurality of the attributes are visual masking strengths of at least oneportion of each image, the visual masking strengths for estimating theamount of encoding artifacts that are not perceptible to a viewer of thevideo sequence after the video sequence has been encoded according tothe method and then decoded.
 11. The method of claim 9, wherein aplurality of the attributes are visual masking strengths of at least oneportion of each image, wherein a visual masking strength for a portionof an image quantifies the complexity of the portion of the image,wherein in quantifying the complexity of a portion of an image, thevisual masking strength provides an indication of the amount ofcompression artifacts that can result from the encoding without visibledistortions in the encoded image after the image is decoded.
 12. Amethod of encoding a plurality of images, the method comprising: a)identifying a plurality of image attributes, each particular imageattribute quantifying the complexity of at least a particular portion ofa particular image, b) identifying a reference attribute that quantifiesthe complexity of the plurality of images, b) identifying quantizationparameters for encoding the plurality of images based on the identifiedimage attributes, reference attribute and the nominal quantizationparameter; c) encoding the plurality of images based on the identifiedquantization parameter; and d) iteratively performing the identifyingand encoding operations to optimize the encoding, wherein a plurality ofdifferent iterations use a plurality of different reference attributes13. The method of claim 12, wherein a plurality of the attributes arevisual masking strengths of at least one portion of each image, thevisual masking strengths for estimating the amount of encoding artifactsthat are not perceptible to a viewer of the video sequence after thevideo sequence has been encoded according to the method and thendecoded.
 14. The method of claim 12, wherein a plurality of theattributes are visual masking strengths of at least one portion of eachimage, wherein a visual masking strength for a portion of an imagequantifies the complexity of the portion of the image, wherein inquantifying the complexity of a portion of an image, the visual maskingstrength provides an indication of the amount of compression artifactsthat can result from the encoding without visible distortions in theencoded image after the image is decoded.
 15. A computer readable mediumstoring a computer program for encoding of a plurality of images in avideo sequence, the computer program comprising sets of instructionsfor: a) iteratively performing an encoding operation that encodes theimages, wherein each encoding operation is based on a nominalquantization parameter, said nominal quantization parameter used todefine quantization parameters for the images, wherein the nominalquantization parameters are different during a plurality of differentiterations of the encoding operation; b) stopping the iterations when anencoding operation satisfies a set of termination criteria.
 16. Thecomputer readable medium of claim 14, wherein the set of terminationcriteria includes the identification of an acceptable encoding of theimages.
 17. The computer readable medium of claim 15, wherein anacceptable encoding of the images is an encoding of the images that iswithin a particular range of a target bit rate.
 18. A computer readablemedium storing a computer program for encoding a plurality of images,the computer program comprising sets of instructions for: a) defining anominal quantization parameter for encoding the images; b) deriving atleast an image-specific quantization parameter for at least one imagebased on the nominal quantization parameter; c) encoding the imagesbased on the image-specific quantization parameter; and d) iterativelyrepeating the defining, deriving, and encoding operations to optimizethe encoding.
 19. The computer readable medium of claim 18, wherein thecomputer program further comprises sets of instructions for: a) derivinga plurality of image-specific quantization parameters for a plurality ofimages based on the nominal quantization parameter; b) encoding theimages based on the image-specific quantization parameters; and c)repeating the defining, deriving, and encoding operations to optimizethe encoding.
 20. The computer readable medium of claim 18 furthercomprising a set of instructions for stopping the iterations when anencoding operation satisfies a set of termination criteria.
 21. Thecomputer readable medium of claim 20, wherein the set of terminationcriteria includes the identification of an acceptable encoding of theimages.
 22. The computer readable medium of claim 21, wherein anacceptable encoding of the images is an encoding of the images that iswithin a particular range of a target bit rate.
 23. A method of encodinga sequence of video images, the method comprising: a) receiving thesequence of video images; b) iteratively examining different encodingsolutions for the sequence of video images to identify an encodingsolution that optimizes image quality while meeting a target bit rateand satisfying a set of constraints regarding flow of encoded datathrough an input buffer of a hypothetical reference decoder for decodingthe encoded video sequence.
 24. The method of claim 23, wherein saiditerative examining comprises for each encoding solution, determiningwhether the hypothetical reference decoder underflows while processingthe encoding solution for any set of images within the video sequence.25. The method of claim 23, wherein said iterative examination ofdifferent encodings comprises: a) simulating the input buffer conditionof hypothetical reference decoder; b) utilizing said simulation toselect the number of bits to optimize image quality while maximizinginput buffer usage at the hypothetical reference decoder; c) re-encodingsaid encoded video images to achieve said optimized buffer usage; and d)performing said simulation, utilization, and re-encoding iterativelyuntil an optimal encoding is identified.
 26. The method of claim 25,wherein simulating the hypothetical reference decoder input buffercondition further comprises considering a rate at which the hypotheticalreference decoder receives encoded data.
 27. The method of claim 25,wherein simulating the hypothetical reference decoder input buffercondition further comprises considering a size of the hypotheticalreference decoder input buffer.
 28. The method of claim 25, whereinsimulating the hypothetical reference decoder input buffer conditionfurther comprises considering an initial removal delay from thehypothetical reference decoder's input buffer.
 29. The method of claim23 further comprising: a) before said iterative examinations,identifying an initial encoding solution that is not based on the set ofconstraints relating to the buffer flow; and b) using the initialencoding solution to start a first examination in said iterativeexaminations.
 30. A computer readable medium storing a computer programfor encoding a sequence of video images in a system having ahypothetical reference decoder with an input buffer, the computerprogram comprising sets of instructions for: a) receiving the sequenceof video images; b) iteratively examining different encoding solutionsfor the sequence of video images to identify an encoding solution thatoptimizes image quality while meeting a target bit rate and satisfying aset of constraints regarding flow of encoded data through an inputbuffer of a hypothetical reference decoder for decoding the encodedvideo sequence.
 31. The computer readable medium of claim 30, whereinthe set of instructions for said iterative examining comprises a set ofinstructions for determining, for each encoding solution, whether thehypothetical reference decoder underflows while processing the encodingsolution for any set of images within the video sequence.
 32. Thecomputer readable medium of claim 30, wherein the set of instructionsfor said iterative examination of different encodings comprises a set ofinstructions for: a) simulating the input buffer condition ofhypothetical reference decoder; b) utilizing said simulation to selectthe number of bits to optimize image quality while maximizing inputbuffer usage at the hypothetical reference decoder; c) re-encoding saidencoded video images to achieve said optimized buffer usage; and d)performing said simulation, utilization, and re-encoding iterativelyuntil an optimal encoding is identified.
 33. The computer readablemedium of claim 32, wherein the set of instructions for simulating thehypothetical reference decoder input buffer condition further comprisesa set of instructions for considering a rate at which the hypotheticalreference decoder receives encoded data.
 34. The computer readablemedium of claim 32, wherein the set of instructions for simulating thehypothetical reference decoder input buffer condition further comprisesa set of instructions for considering a size of the hypotheticalreference decoder input buffer.
 35. The computer readable medium ofclaim 32, wherein the set of instructions for simulating thehypothetical reference decoder input buffer condition further comprisesa set of instructions for considering an initial removal delay from thehypothetical reference decoder's input buffer.
 36. The computer readablemedium of claim 30, wherein the computer program further comprises setsof instructions for: a) before said iterative examinations, identifyingan initial encoding solution that is not based on the set of constraintsrelating to the buffer flow; and b) using the initial encoding solutionto start a first examination in said iterative examinations.